using SqlSugar;

namespace ChatBackend.Infrastructure
{
    public abstract class BaseRepository<T> where T : class, new()
    {
        protected readonly ISqlSugarClient _db;
        protected readonly ILogger _logger;

        protected BaseRepository(ISqlSugarClient db, ILogger logger)
        {
            _db = db;
            _logger = logger;
        }

        protected async Task<TResult> ExecuteWithRetry<TResult>(Func<Task<TResult>> operation, int maxRetries = 3)
        {
            for (int i = 0; i < maxRetries; i++)
            {
                try
                {
                    return await operation();
                }
                catch (Exception ex) when (i < maxRetries - 1)
                {
                    _logger.LogWarning($"操作失败，正在重试 ({i + 1}/{maxRetries}): {ex.Message}");
                    await Task.Delay(100 * (i + 1)); // 递增延迟
                }
            }

            // 最后一次尝试，不捕获异常
            return await operation();
        }

        protected async Task<T?> SafeFirstOrDefaultAsync(ISugarQueryable<T> queryable)
        {
            return await ExecuteWithRetry(async () =>
            {
                try
                {
                    var list = await queryable.ToListAsync();
                    return list.FirstOrDefault();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"查询失败: {ex.Message}");
                    return null;
                }
            });
        }

        protected async Task<List<T>> SafeToListAsync(ISugarQueryable<T> queryable)
        {
            return await ExecuteWithRetry(async () =>
            {
                try
                {
                    return await queryable.ToListAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"查询列表失败: {ex.Message}");
                    return new List<T>();
                }
            });
        }

        protected async Task<bool> SafeExecuteAsync(Func<Task<bool>> operation)
        {
            return await ExecuteWithRetry(async () =>
            {
                try
                {
                    return await operation();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"执行操作失败: {ex.Message}");
                    return false;
                }
            });
        }

        protected async Task<int> SafeExecuteCommandAsync(Func<Task<int>> operation)
        {
            return await ExecuteWithRetry(async () =>
            {
                try
                {
                    return await operation();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"执行命令失败: {ex.Message}");
                    return 0;
                }
            });
        }
    }
}
